<?php

namespace App\Console\Commands;

use App\Http\Controllers\Admin\Traits\AdminTrait;
use App\Models\Admin\AdminBillMonth;
use App\Models\Admin\AdminSetting;
use App\Models\Admin\Company;
use App\Models\Admin\Document;
use App\Models\Admin\DomesticBill;
use App\Models\Admin\Order;
use App\Notifications\SiteNotice;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class MakeDomesticBill extends Command
{

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'make:bill';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'make domestic bill';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //判断当月是否已经运行过
        $is_run=AdminBillMonth::where('month','like',date('Y-m').'%')->count();
        if($is_run) return;
        $admin_setting=AdminSetting::pluck('value','name');
        $companies = Company::where('model',2)->cursor();
        if ($companies->isNotEmpty()){
            try {
                DB::transaction(function ()use ($companies,$admin_setting){
                    $pay_notice_days=$admin_setting['pay_notice_days']?? 6;
                    $pay_forbid_days=$admin_setting['pay_forbid_days']?? 7;

                    $payment_days = date('Y-m',strtotime('-1 month'));
                    $payment_days_tz = date('Y/m',strtotime('-1 month'));
                    $begin_time = strtotime(date('Y-m-01',strtotime('-1 month')));
                    $end_time = strtotime(date('Y-m-01'))-1;
                    $today_stamp=strtotime(date('Y-m-d'));
                    $today_tz=date('Y/m/d');
                    foreach ($companies as $company){
                        //判断用户上个月有没有到期
                        if($company->end_time<$end_time) continue;
                        //判断账期内是否有账单，有则不生成
                        $bill = DomesticBill::where('payment_days',$payment_days)->where('company_id',$company->id)->where('pay_status','<',2)->get();
                        if ($bill->isNotEmpty()) continue;
                        //判断有配送金额，没有则不生成
                        $send_money = Order::where('company_id',$company->id)->where('is_prior_payment',0)->whereIn('order_status',[1,2,3])->whereBetween('send_time',[$begin_time,$end_time])->sum("send_money");
                        $return_money = Order::where('company_id',$company->id)->where('is_prior_payment',0)->whereIn('order_status',[1,2,3])->whereBetween('send_time',[$begin_time,$end_time])->sum("return_money");
                        $send_money=$send_money-$return_money;
                        if ($send_money <= 0) continue;
                        $commission_rate = str_replace("‰","",$company->commission_rate);
                        $commission = sprintf("%.2f",(($send_money*$commission_rate)/1000));
                        $order_sn=$this->sn_job('YJZD');
                        DomesticBill::create([
                            'company_id' => $company->id,
                            'order_sn' => $order_sn,
                            'payment_days' => $payment_days,
                            'original_send_money' => $send_money,
                            'original_commission' => $commission,
                            'original_commission_rate' => $company->commission_rate,
                            'send_money' => $send_money,
                            'commission' => $commission,
                            'commission_rate' => $company->commission_rate,
                            'zero_money' => 0,
                            'real_money' => $commission,
                            'zero_status' => 0,
                            'pay_status' => 0,
                            'notice_days' => $today_stamp+($pay_notice_days*86400),//取配置
                            'forbid_days' => $today_stamp+($pay_forbid_days*86400),//取配置
                            'created_at' => time(),
                            'updated_at' => time(),
                        ]);
                        //发送通知
                        $doc_data=[
                            'type'=>2,
                            'title'=>config('app.zd_title_create'),
                            'status'=>1,
                            'author'=>'菜东家集团',
                            'content'=>"<p>尊敬的菜东家合伙人，您好<br />&nbsp; &nbsp;&nbsp;<br />&nbsp; &nbsp; 您{$payment_days_tz}账期的货到付款佣金账单已生成，账单号{$order_sn}，请及时对账和付款，以免影响系统的正常使用，感谢您的支持！<br />&nbsp; &nbsp; &nbsp;&nbsp;<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;菜东家集团<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{$today_tz}</p>",
                            'product_type'=>2,
                            'document_type'=>5,
                        ];
                        $res_tz=Document::create($doc_data);
                        $company->notify(new SiteNotice($res_tz));
                    }
                    AdminBillMonth::create(['month'=>date('Y-m-d')]);//记录
                },5);
            }catch (\Exception $exception){
                Log::channel('commands')->error('make domestic bill err',['errTrace'=>$exception->getTrace(),'errInfo'=>$exception->getMessage()]);
            }
        }
    }

    protected function sn_job($prefix){
        try{
            $key = $prefix;
            if (!Redis::exists($key)){
                $end_time = strtotime('23:59:59')-time();
                Redis::setex($key, $end_time, 0);
            }
            return $prefix.date('Ymd').sprintf("%04d",Redis::incr($key));
        }catch(\Exception $e){
            return $prefix.date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        }
    }
}
